<template>
  <div class="console">
    <!--数据卡片-->
    <n-grid cols="1 s:2 m:3 l:4 xl:4 2xl:4" responsive="screen" :x-gap="12" :y-gap="8">
      <n-grid-item>
        <NCard
          title="车辆数"
          :segmented="{ content: true, footer: true }"
          size="small"
          :bordered="false"
        >
          <template #header-extra>
            <n-tag type="warning">辆</n-tag>
          </template>
          <div class="py-1 px-1 flex justify-between">
            <CountTo :startVal="1" :endVal="currentDayDataVO.carNumber" class="text-3xl" />
          </div>
           <template #footer>
            <div class="flex justify-between">
              <n-skeleton v-if="loading" :width="100" size="medium" />
              <template v-else>
                <div class="text-sn"> 昨日车辆总数： </div>
                <div class="text-sn">
                  <CountTo :startVal="1"  :endVal="currentDayDataVO.yesterdayCarNumber" />
                </div>
              </template>
            </div>
          </template>
        </NCard>
      </n-grid-item>
      <n-grid-item>
        <NCard
          title="货物总净重"
          :segmented="{ content: true, footer: true }"
          size="small"
          :bordered="false"
        >
          <template #header-extra>
            <n-tag type="info">KG</n-tag>
          </template>
          <div class="py-1 px-1 flex justify-between">
            <CountTo
              :startVal="1"
              :endVal="currentDayDataVO.allNetWeight"
              class="text-3xl"
            />
          </div>
          <template #footer>
            <div class="flex justify-between">
              <n-skeleton v-if="loading" :width="100" size="medium" />
              <template v-else>
                <div class="text-sn"> 昨日总净重： </div>
                <div class="text-sn">
                  <CountTo  :startVal="1" :endVal="currentDayDataVO.yesterdayAllNetWeight" />
                </div>
              </template>
            </div>
          </template>
        </NCard>
      </n-grid-item>
      <n-grid-item>
        <NCard
          title="货物总价"
          :segmented="{ content: true, footer: true }"
          size="small"
          :bordered="false"
        >
          <template #header-extra>
            <n-tag type="warning">元</n-tag>
          </template>
          <div class="py-1 px-1 flex justify-between">
            <CountTo
              prefix="￥"
              :startVal="1"
              :endVal="currentDayDataVO.allTotal"
              class="text-3xl"
            />
          </div>
          <template #footer>
            <div class="flex justify-between">
              <n-skeleton v-if="loading" :width="100" size="medium" />
              <template v-else>
                <div class="text-sn"> 昨日货物总价： </div>
                <div class="text-sn">
                  <CountTo :startVal="1" prefix="￥" :endVal="currentDayDataVO.yesterdayAllTotal" />
                </div>
              </template>
            </div>
          </template>
        </NCard>
      </n-grid-item>
      <n-grid-item>
        <NCard
          title="过磅费"
          :segmented="{ content: true, footer: true }"
          size="small"
          :bordered="false"
        >
          <template #header-extra>
            <n-tag type="error">元</n-tag>
          </template>
          <div class="py-1 px-1 flex justify-between">
            <CountTo prefix="￥" :startVal="1" :endVal="currentDayDataVO.allWeightFee" class="text-3xl" />
          </div>
          <template #footer>
            <div class="flex justify-between">
              <n-skeleton v-if="loading" :width="100" size="medium" />
              <template v-else>
                <div class="text-sn"> 昨日总过磅费： </div>
                <div class="text-sn">
                  <CountTo prefix="￥" :startVal="1" :endVal="currentDayDataVO.yesterdayAllWeightFee" />
                </div>
              </template>
            </div>
          </template>
        </NCard>
      </n-grid-item>
    </n-grid>

    <!--导航卡片-->
    <div class="mt-4">
      <!-- 修改为在所有屏幕尺寸下都占据全部宽度 -->
      <NRow :gutter="24">
      <NCol :span="7">
        <n-card content-style="padding: 0;" :bordered="false">
         <div ref="pieChartRef" :style="{ height: '300px', width: '100%' }"></div>
        </n-card>
      </NCol>
      <NCol :span="17">
        <n-card content-style="padding: 0;" :bordered="false">
         <div ref="lineChartRef" :style="{ height: '300px', width: '100%' }"></div>
        </n-card>
      </NCol>
      </NRow>
    </div>

    <!--访问量 | 流量趋势-->
    <VisiTab :selectedGoodsType="selectedGoodsType" />
  </div>
</template>
<script lang="ts" setup>
    import { ref, onMounted, reactive, Ref } from 'vue';
    import { getCurrentDayData, getCurrentGoodsType,getLastSevenDayAveragePrice,getLastMonthDayFee,getPriceTrendByGoodsType} from '@/api/weight/weight';
    import VisiTab from './components/VisiTab.vue';
    import { useECharts } from '@/hooks/web/useECharts';

  const loading = ref(true);


  // getCurrentDayGoodsWeight接口返回值类型定义
  interface GoodsWeightItem {
    goodsName: string;
    allNet: number;
    goodsType: number
  }

    interface GoodsPriceItem {
    dateStr: string;
    goodsName: string;
    goodsPrice:number;
  }

  // 用于存储getCurrentDayGoodsWeight接口返回的商品重量数据
  const goodsWeightData = ref<GoodsWeightItem[]>([]);

  const priceLastSevenGoodsData = ref<GoodsPriceItem[]>([]);
  
  // 存储当前选中的商品类型，用于同步更新VisiTab组件
  const selectedGoodsType = ref<number | null>(null);

  // 饼图配置对象
  const option = reactive<Record<string, any>>({});
  // 饼图容器引用
  const pieChartRef = ref<HTMLDivElement | null>(null);
  // const { setOptions: setPieChartOptions } = useECharts(pieChartRef as Ref<HTMLDivElement>);
  const { setOptions: setPieChartOptions, getInstance: getPieInstance } = useECharts(pieChartRef as any)
  // 曲线图容器引用
  const lineChartRef = ref<HTMLDivElement | null>(null);
  const { setOptions: setLineChartOptions } = useECharts(lineChartRef as Ref<HTMLDivElement>);
 
 const currentDayDataVO = reactive({
        carNumber: 0,
        allNetWeight: 0,
        allTotal: 0,
        allWeightFee: 0,
        yesterdayCarNumber: 0,
        yesterdayAllNetWeight: 0,
        yesterdayAllTotal: 0,
        yesterdayAllWeightFee: 0,
    })

// 更新折线图的函数
  function updateLineChart(data: GoodsPriceItem[]) {
    const hasData = data && data.length > 0 && data.some(d => d.goodsPrice > 0)

    const goodsNames = [...new Set(data.map(d => d.goodsName))]
    const dates = [...new Set(data.map(d => d.dateStr))].sort() // 按时间排序

    const colors = ['#69c0ff', '#ff9c6e', '#5cdbd3', '#b37feb', '#ff6700', '#006400']

    const series = hasData
      ? goodsNames.map((name, idx) => {
          const color = colors[idx % colors.length]
          return {
            name,
            type: 'line' as const,
            smooth: true,
            symbol: 'circle',
            symbolSize: 6,
            data: dates.map(date => {
              const item = data.find(d => d.goodsName === name && d.dateStr === date)
              return item ? item.goodsPrice : 0
            }),
            lineStyle: { width: 3, color },
            itemStyle: { color },
            areaStyle: {
              color: {
                type: 'linear',
                x: 0, y: 0, x2: 0, y2: 1,
                colorStops: [
                  { offset: 0, color: `${color}44` },
                  { offset: 1, color: `${color}05` }
                ]
              }
            }
          }
        })
      : [
          {
            name: '暂无数据',
            type: 'line' as const,
            data: [0],
            lineStyle: { color: '#ccc' },
            itemStyle: { color: '#ccc' },
            areaStyle: { color: '#f5f5f5' }
          }
        ]

    const finalDates = hasData ? dates : ['暂无数据']

    const option = {
      title: {
        text: hasData ? '近七日价格趋势' : '暂无价格数据',
        left: 'center',
        textStyle: { fontSize: 16, fontWeight: 'normal' }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          const date = params[0]?.axisValue
          let res = `${date}<br/>`
          params.forEach((p: any) => {
            res += `${p.marker}${p.seriesName}: ${p.value} 元<br/>`
          })
          return res
        }
      },
      legend: { data: series.map(s => s.name), top: '30px' },
      grid: { left: '3%', right: '4%', bottom: '3%', top: '80px', containLabel: true },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: finalDates,
        axisLabel: {
          formatter: (val: string) =>
            val === '暂无数据' ? val : `${new Date(val).getMonth() + 1}/${new Date(val).getDate()}`
        }
      },
      yAxis: {
        type: 'value',
        name: '单价 (元)',
        axisLabel: { formatter: '{value} 元' }
      },
      series
    }

    setLineChartOptions(option)
  }

  onMounted(async () => {
    try {
      // 调用API获取数据
      const result = await getCurrentDayData();
      if (result) {
        // 确保只有非null和非undefined的值才会覆盖默认值
        Object.keys(currentDayDataVO).forEach(key => {
          if (result[key] !== null && result[key] !== undefined) {
            currentDayDataVO[key] = result[key];
          }
        });
        console.log(currentDayDataVO)
      }
      
      // 调用商品重量数据接口
      const goodsWeightResult = await getCurrentGoodsType();
      if (goodsWeightResult) {
        if (goodsWeightResult.result && Array.isArray(goodsWeightResult.result)) {
          goodsWeightData.value = goodsWeightResult.result;
        } else if (Array.isArray(goodsWeightResult)) {
          goodsWeightData.value = goodsWeightResult;
        }
      }

       // 调用商品近7日平均价
      const goodsPriceResult = await getLastSevenDayAveragePrice();
      if (goodsPriceResult) {
        if (goodsPriceResult.result && Array.isArray(goodsPriceResult.result)) {
          priceLastSevenGoodsData.value = goodsPriceResult.result;
        } else if (Array.isArray(goodsPriceResult)) {
          priceLastSevenGoodsData.value = goodsPriceResult;
        }
      }


    } catch (error) {
      console.error('获取数据失败:', error);
    } finally {
      // 设置为加载完成状态
      loading.value = false;
    }
    
    // 检查是否有大于0的数据
    const hasValidData = goodsWeightData.value.some(item => item.allNet > 0);

    // 设置饼图配置
    option.series = [
      {
        type: 'pie',
        data: hasValidData 
          ? goodsWeightData.value.map(item => ({
              value: item.allNet,
              name: item.goodsName+' '+item.allNet,
              goodsType: item.goodsType,
            }))
          : [
              {
                value: 100,
                name: '暂无数据'
              }
            ],
        roseType: 'area'
      }
    ];
    
    setPieChartOptions(option);
    
    const pieInstance = getPieInstance()
    if (pieInstance) {
      pieInstance.on('click', async (params) => {
        const { goodsType } = params.data;
        // 更新选中的商品类型，用于同步更新VisiTab组件
        selectedGoodsType.value = goodsType;
        try {
          console.log(goodsType)
          const trendData = await getPriceTrendByGoodsType(goodsType); 
          updateLineChart(trendData);
        } catch (error) {
          updateLineChart([]);
        }
      });
    }
    // 检查是否有有效的价格数据
    const hasValidPriceData = priceLastSevenGoodsData.value.some(item => 
      item.goodsPrice !== null && item.goodsPrice !== undefined && item.goodsPrice > 0
    );
    
    // 按商品名称分组数据
    const goodsGroupMap = new Map<string, {dateStr: string, goodsPrice: number}[]>();
    
    // 遍历数据进行分组
    priceLastSevenGoodsData.value.forEach(item => {
      if (!goodsGroupMap.has(item.goodsName)) {
        goodsGroupMap.set(item.goodsName, []);
      }
      goodsGroupMap.get(item.goodsName)?.push(item);
    });
    
    // 获取所有日期并排序（确保按时间顺序显示）
    const allDates = [...new Set(priceLastSevenGoodsData.value.map(item => item.dateStr))]
      .sort((a, b) => new Date(a).getTime() - new Date(b).getTime());
    
    // 定义颜色数组，用于不同商品的曲线
    const colors = [
      '#69c0ff', '#ff9c6e', '#5cdbd3', '#ff6700', 
      '#ff4500', '#006400', '#722ed1', '#13c2c2',
      '#faad14', '#52c41a', '#1890ff', '#eb2f96',
      '#ff7a45', '#597ef7', '#fa541c', '#13c2c2',
      '#2f54eb', '#722ed1', '#faad14', '#fadb14'
    ];
    
    // 创建series数据
    const seriesData = Array.from(goodsGroupMap.entries()).map(([goodsName, items], index) => {
      // 为每个日期找到对应的价格，如果没有则显示0
      const data = allDates.map(date => {
        const item = items.find(i => i.dateStr === date);
        return item?.goodsPrice || 0;
      });
      
      const color = colors[index % colors.length];
      
      return {
        name: goodsName,
        type: 'line' as const,
        yAxisIndex: 0,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        data: data,
        lineStyle: {
          width: 3,
          color: color
        },
        itemStyle: {
          color: color
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: `${color}33` // 33是十六进制的51，约20%透明度
              },
              {
                offset: 1,
                color: `${color}0D` // 0D是十六进制的13，约5%透明度
              }
            ]
          }
        }
      };
    });
    
    // 如果没有有效数据，显示提示信息
    let finalSeriesData = seriesData;
    let finalDates = allDates;
    
    if (!hasValidPriceData) {
      finalDates = ['暂无数据'];
      // finalSeriesData = [
      //   {
      //     name: '暂无数据',
      //     type: 'line' as const,
      //     yAxisIndex: 0,
      //     smooth: true,
      //     symbol: 'circle',
      //     symbolSize: 8,
      //     data: [0],
      //     lineStyle: {
      //       width: 3,
      //       color: '#69c0ff'
      //     },
      //     itemStyle: {
      //       color: '#69c0ff'
      //     }
      //   }
      // ];
    }
    
    const lineOption = {
      title: {
        text: '近七日物品平均价',
        left: 'center',
        textStyle: {
          fontSize: 16,
          fontWeight: 'normal'
        }
      },
      tooltip: {
        trigger: 'axis',
        formatter: (params: any) => {
          let result = `${params[0].axisValue}<br/>`;
          params.forEach((param: any) => {
            result += `${param.marker}${param.seriesName}: ${param.value}<br/>`;
          });
          return result;
        }
      },
      legend: {
        data: finalSeriesData.map(series => series.name),
        top: '30px'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        top: '80px',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: finalDates,
        axisLabel: {
          formatter: (value: string) => {
            // 格式化日期显示，只显示月-日部分
            if (value !== '暂无数据') {
              const date = new Date(value);
              return `${date.getMonth() + 1}-${date.getDate()}`;
            }
            return value;
          }
        }
      },
      yAxis: [
        {
          type: 'value',
          name: '价格 (元)',
          nameTextStyle: {
            padding: [0, 0, 0, 1900]
          },
          position: 'left',
          axisLabel: {
            formatter: '{value} 元'
          }
        }
      ],
      series: finalSeriesData
    };
    
    // 渲染曲线图
    setLineChartOptions(lineOption);
  });
</script>

<style lang="less" scoped></style>